<?php
namespace App\Services;
use GuzzleHttp\Client;
use App\Models\Officialusersinfo;
use App\Models\Users;
use App\Models\Usersauthority;
use App\Services\KflistsService;
use App\Services\CommonService;
use Illuminate\Support\Facades\Storage;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Redis;
use Log,Exception,Config;
use Symfony\Component\Cache\Adapter\RedisAdapter;

class WechatoffiaccountService
{
    /**
    * 修改symfony/cache缓存方式为redis
    * @param array $config
    * @return \EasyWeChat\OfficialAccount\Application
    */
    public static function officialAccount()
    {
        $config = Config::get("weixin.offiaccount.ttwl");
        $app = Factory::officialAccount($config);
        $predis = app('redis')->connection()->client();
        $cache = new RedisAdapter($predis);
        $app->rebind('cache', $cache);
        return $app;
    }

    public static function officialAccessToken($forth)
    {
        $official = self::officialAccount();
        $accessToken = $official->access_token;
        if ($forth) {
            $token = $accessToken->getToken(true);
        } else {
            $token = $accessToken->getToken();
        }
        return $token;
    }

    // 保存/更新用户扫码登录
    public static function officialUsersInfoLogin($FromUserName,$Event,$EventKey)
    {
        $official = self::officialAccount();
        $usersInfo = $official->user->get($FromUserName);
        $unionid = isset($usersInfo["unionid"]) ? $usersInfo["unionid"] : "";
        $userInfoExist = Users::getUsersByUnionid($unionid);
        try {
            $usersId = CommonService::getRandomCode();
            // $nickname = isset($usersInfo["nickname"]) ? $usersInfo["nickname"] : $usersId;
            // if ($usersInfo["sex"] == 1) {
            //     $headimgurl = isset($usersInfo["headimgurl"]) ? $usersInfo["headimgurl"] : "https://wwcdn.weixin.qq.com/node/wework/images/kf_head_image_url_3.png";
            // } else {
            //     $headimgurl = isset($usersInfo["headimgurl"]) ? $usersInfo["headimgurl"] : "https://wwcdn.weixin.qq.com/node/wework/images/kf_head_image_url_4.png";
            // }
            if (!isset($userInfoExist->id)) {
                // 判断是否是登录用户
                if(strpos($EventKey,'login-') !== false){
                    $token = str_replace(["login-","qrscene_"], "", $EventKey);
                    try {
                        $address = $usersInfo["country"].$usersInfo["province"].$usersInfo["city"];
                    } catch (Exception $e) {
                        $address = "";
                    }
                    $users_id = Users::creatUsersByOfficial($usersInfo["openid"],$usersInfo["sex"],$address,$usersInfo["unionid"],$token,$usersInfo["subscribe_time"]);
                    Usersauthority::createUsersAuthority($users_id,1,1);
                    return self::welcomeSubscribe();
                } else {
                    return self::welcomeSubscribe();
                }
            } else {
                // 判断是否是登录用户
                if(strpos($EventKey,'login-') !== false){
                    $token = str_replace(["login-","qrscene_"], "", $EventKey);
                    try {
                        $address = $usersInfo["country"].$usersInfo["province"].$usersInfo["city"];
                    } catch (Exception $e) {
                        $address = "";
                    }
                    Users::updateUsersByOfficial($usersInfo["openid"],$usersInfo["sex"],$address,$usersInfo["unionid"],$token);
                    return "恭喜您，账号登录成功！";
                } else {
                    return self::welcomeSubscribe();
                }
            }
        } catch (Exception $e) {
            Log::info($e);
            if(strpos($usersInfo["qr_scene_str"],'login-') !== false){
                return '登录异常,请联系客服处理！';
            } else {
                return '公众号异常,请联系客服处理！';
            }
        }
    }

    public static function welcomeSubscribe()
    {
        $welcomemsg =  "【天天外链】支持链接一键跳转公众号/小程序/企业微信/微信群/个人微信/小商店/视频号。🤗\n<a href=\"weixin://bizmsgmenu?msgmenucontent=查看演示案例&msgmenuid=10001\">→ 查看演示案例</a>\n<a href=\"weixin://bizmsgmenu?msgmenucontent=创建推广链接&msgmenuid=10002\">→ 创建推广链接</a>\n获取其他服务\n<a href=\"weixin://bizmsgmenu?msgmenucontent=查看支持的平台&msgmenuid=10003\">→ 查看支持的平台</a>\n<a href=\"weixin://bizmsgmenu?msgmenucontent=联系微信客服&msgmenuid=20001\">→ 联系微信客服</a>\n<a href=\"weixin://bizmsgmenu?msgmenucontent=获取小程序路径&msgmenuid=10006\">→ 获取小程序路径</a>\n🥰快来免费创建链接体验吧！🥰";
        return $welcomemsg;
    }
}
